package com.aaa.marketresearch.android.app;

import android.app.*;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.*;
import com.aaa.marketresearch.android.data.UserInfo;
import com.aaa.marketresearch.android.data.domain.FamilyMember;
import com.aaa.marketresearch.android.data.domain.Market;
import com.aaa.marketresearch.android.service.HttpClient;
import com.aaa.marketresearch.android.util.EasyDateFormat;
import com.aaa.marketresearch.android.util.SimpleLog;
import com.aaa.marketresearch.android.util.connector.IDataTextResponse;
import com.aaa.marketresearch.android.widget.MarketAdapter;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author Nail
 */
public class FamilyMemberScreen extends FragmentActivity {

    private AutoCompleteTextView editTextProfession;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_family_member_screen);
        this.editTextProfession = (AutoCompleteTextView) findViewById(R.id.familyMemberProfessionField);
    }

    @Override
    protected void onResume() {
        super.onResume();

        final FamilyMember familyMember = UserInfo.getInstance().getCurrentFamilyMember();

        ((EditText) findViewById(R.id.familyMemberNameField)).setText(familyMember.getName());

        Button birthdayButton = (Button) findViewById(R.id.familyMemberBirthdayField);

        birthdayButton.setText(EasyDateFormat.format(familyMember.getBirthday()));


        Spinner spinnerGender = (Spinner) findViewById(R.id.familyMemberGenderField);
        ArrayAdapter<CharSequence> adapterGender = ArrayAdapter.createFromResource(this, R.array.familyMemberGender_Array, android.R.layout.simple_spinner_item);
        adapterGender.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerGender.setAdapter(adapterGender);

        int spinnerGenderPos = adapterGender.getPosition(familyMember.getGender());
        spinnerGender.setSelection(spinnerGenderPos);


        this.editTextProfession.setText(familyMember.getProfession());

        this.loadProfessions();
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();

        FragmentManager fragmentManager = this.getSupportFragmentManager();

        newFragment.show(fragmentManager, "datePicker");
    }

    public static class DatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar calendar = Calendar.getInstance();

            Button birthdayButton = (Button) this.getActivity().findViewById(R.id.familyMemberBirthdayField);
            String name = birthdayButton.getText().toString();
            Date date = EasyDateFormat.parse(name);
            calendar.setTimeInMillis(date.getTime());

            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            final Calendar calendar = Calendar.getInstance();
            calendar.set(year, month, day);
            Date date = new Date(calendar.getTimeInMillis());

            Button birthdayButton = (Button) this.getActivity().findViewById(R.id.familyMemberBirthdayField);
            String name = EasyDateFormat.format(date);
            birthdayButton.setText(name);
        }
    }

    public void saveButtonClick(View view) {
        SimpleLog.info("saveButtonClick");

        final FamilyMember familyMember = UserInfo.getInstance().getCurrentFamilyMember();

        Button birthdayButton = (Button) this.findViewById(R.id.familyMemberBirthdayField);
        String birthdayText = birthdayButton.getText().toString();
        Date birthdayDate = EasyDateFormat.parse(birthdayText);

        familyMember.setBirthday(birthdayDate);

        String name = ((EditText) findViewById(R.id.familyMemberNameField)).getText().toString();
        familyMember.setName(name);

        String gender = ((Spinner) findViewById(R.id.familyMemberGenderField)).getSelectedItem().toString();
        familyMember.setGender(gender);

        String profession = ((AutoCompleteTextView) findViewById(R.id.familyMemberProfessionField)).getText().toString();
        familyMember.setProfession(profession);

        HttpClient httpClient = new HttpClient(this.getApplicationContext());
        httpClient.saveFamilyMember(familyMember, new IDataTextResponse() {
            @Override
            public void onTextResponse(String text) {
                SimpleLog.info("saved");
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(FamilyMemberScreen.this);
                alertDialog.setMessage("Сохранен");
                alertDialog.setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                FamilyMemberScreen.this.finish();
                            }
                        }
                );
                alertDialog.show();
            }

            @Override
            public void onError() {
                SimpleLog.info("error");
            }
        });
    }


    private void loadProfessions() {
        HttpClient httpClient = new HttpClient(this.getApplicationContext());
        httpClient.loadProfessions(new IDataTextResponse() {
            @Override
            public void onTextResponse(String json) {
                if (json != null) {
                    JSONParser parser = new JSONParser();
                    JSONArray data = null;
                    try {
                        data = (JSONArray) parser.parse(json);
                    } catch (ParseException e) {
                        SimpleLog.error(e.toString());
                    }
                    Object obj = null;

                    int n = data.size();
                    if (n > 0) {
                        List<String> profession = new ArrayList<>(n);
                        for (int i = 0; i < n; i++) {
                            String prof = (String) data.get(i);
                            profession.add(prof);
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(FamilyMemberScreen.this, android.R.layout.simple_list_item_1, profession);
                        FamilyMemberScreen.this.editTextProfession.setAdapter(adapter);
                    }
                }
            }

            @Override
            public void onError() {
                SimpleLog.info("error");
            }
        });
    }


}